from django.contrib.auth.hashers import check_password

from utils import restful
from .models import User


def register(request):
    username = request.POST.get('username')
    data = request.POST.dict()  # 打包前端传递的所有字段
    if User.objects.filter(username=username):
        return restful.params_error(message='用户名已存在')
    else:
        user = User(**data)
        user.save()
        result = {
            'id': user.id,
            'username': user.username,
            'name': user.name,
            'id_card': user.id_card,
            'sex': user.sex,
            'phone': user.phone,
        }
        return restful.ok(data=result)


def login(request):
    username = request.POST.get('username')
    password = request.POST.get('password')
    try:
        user = User.objects.get(username=username)
    except:
        return restful.params_error(message='用户名不存在')
    if check_password(password, user.password, preferred='pbkdf2_sha256'):
        result = {
            'id': user.id,
            'username': user.username,
            'name': user.name,
            'id_card': user.id_card,
            'sex': user.sex,
            'phone': user.phone,
        }
        return restful.ok(data=result)
    return restful.params_error(message='用户名或密码错误')
